#include "SHT2x.h"
//#include "delay.h"
#include "myiic.h"
#include<stdio.h>


u8 static SHT2x_Init(uint8_t n)
{
	u8 err;
   IIC_Init(n);
   err = SHT2x_SoftReset();
	delay_us(10000);  
	return err;
}

u8 SHT2x_SoftReset(void) //SHT20软件复位
{
	u8 err=0;
	IIC_Start();
	IIC_Send_Byte(0x80);
	err = IIC_Wait_Ack();
	IIC_Send_Byte(0xFE);
	err = IIC_Wait_Ack();
	IIC_Stop();
	//rt_kprintf("SHT2x_SoftReset:%d\r\n",err);
	return err;
}
//获取温度
float SHT2x_GetTempPoll(uint8_t n)
{
    float TEMP;
    u8 ack, tmp1, tmp2;
    u16 ST;
    u16 i=0;

    SHT2x_Init(n);

    IIC_Start();				//发送IIC开始信号
    IIC_Send_Byte(I2C_ADR_W);			//IIC发送一个字节 
	ack = IIC_Wait_Ack();	
	//rt_kprintf("IIC_Send_Byte:%d\r\n",ack);
	IIC_Send_Byte(TRIG_TEMP_MEASUREMENT_POLL);
	ack = IIC_Wait_Ack();
	//rt_kprintf("TRIG_TEMP_MEASUREMENT_POLL:%d\r\n",ack);
    do {
        delay_us(10000);               
        IIC_Start();				//发送IIC开始信号
        IIC_Send_Byte(I2C_ADR_R);	
			  i++;
			  ack = IIC_Wait_Ack();
			  if(i==100)break;
    } while(ack!=0);
	//rt_kprintf("I2C_ADR_R i:%d\r\n",i);
	//rt_kprintf("I2C_ADR_R:%d\r\n",ack);
    tmp1 = IIC_Read_Byte(1);
    tmp2 = IIC_Read_Byte(1);
	IIC_Read_Byte(0);
    IIC_Stop();
    //rt_kprintf("SHT2x_GetTempPoll: %d=>0x%x 0x%x \r\n",n,tmp1,tmp2);
    ST = (tmp1 << 8) | (tmp2 << 0);
	
    ST &= ~0x0003;
    TEMP = ((float)ST * 0.00268127) - 46.85;

    return (TEMP);	  
}
//获取湿度
float SHT2x_GetHumiPoll(uint8_t n)
{
    float HUMI;
    u8 ack, tmp1, tmp2;
    u16 SRH;
	u16 i=0;
    
	SHT2x_Init(n);
	
    IIC_Start();				//发送IIC开始信号
    IIC_Send_Byte(I2C_ADR_W);			//IIC发送一个字节 
		ack = IIC_Wait_Ack();	
		IIC_Send_Byte(TRIG_HUMI_MEASUREMENT_POLL);
		ack = IIC_Wait_Ack();    
    do {
       delay_us(10000);               
        IIC_Start();				//发送IIC开始信号
        IIC_Send_Byte(I2C_ADR_R);	
			  i++;
			  ack = IIC_Wait_Ack();
			  if(i==1000)break;
    } while(ack!=0);
    
    tmp1 = IIC_Read_Byte(1);
   
    tmp2 = IIC_Read_Byte(1);
     IIC_Read_Byte(0);
    IIC_Stop();
    
    SRH = (tmp1 << 8) | (tmp2 << 0);
    SRH &= ~0x0003;
    HUMI = ((float)SRH * 0.00190735) - 6;
    //rt_kprintf("SHT2x_GetTempPoll: %d=>0x%x 0x%x \r\n",n,HUMI);
    return (HUMI);
}


